package cn.mehoyo.certificateGeneration.common.util;

import lombok.extern.slf4j.Slf4j;
import org.xbill.DNS.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DnsWaitUtil {

    /**
     * 等待 DNS TXT 记录传播（ACME 验证前调用）
     *
     * @param domain     域名，例如 "example.com"
     * @param expectedTxt 期望的 TXT 值（即 challenge.getDigest()）
     * @param nameServer  指定 DNS 服务器（例如 "1.1.1.1"）
     * @param timeoutSec  最大等待时间（秒）
     * @throws Exception 如果超时或解析出错
     */
    public static void waitForDnsPropagation(String domain, String expectedTxt, String nameServer, int timeoutSec) throws Exception {
        String recordName = "_acme-challenge." + domain;
        long endTime = System.currentTimeMillis() + timeoutSec * 1000L;

        while (System.currentTimeMillis() < endTime) {
            List<String> records = queryTxt(recordName, nameServer);
            if (records.stream().anyMatch(r -> r.contains(expectedTxt))) {
                log.info("[ACME] DNS 记录已生效:{} " , records);
                return;
            }
            log.info("[ACME] 等待 DNS 生效中... 当前解析结果:{} " , records);
            Thread.sleep(5000);
        }

        throw new RuntimeException("等待 DNS 记录传播超时: " + recordName);
    }

    private static List<String> queryTxt(String recordName, String nameServer) throws Exception {
        Lookup lookup = new Lookup(recordName, Type.TXT);
        lookup.setCache(null);
        SimpleResolver resolver = new SimpleResolver(nameServer);
        resolver.setTimeout(3);
        lookup.setResolver(resolver);
        Record[] records = lookup.run();

        List<String> result = new ArrayList<>();
        if (records != null) {
            for (Record r : records) {
                if (r instanceof TXTRecord) {
                    TXTRecord txt = (TXTRecord) r;
                    result.add(String.join("", txt.getStrings()));
                }
            }
        }
        return result;
    }
}
